package common;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.google.common.base.Function;

/**
 * PArent class for all the page objects with common functionality and
 * handle of timing issues
 * Reference : http://www.jeromemueller.ch/archives/311/webdriver-staleelementreferenceexception
 */

public class PageObjectCommonFunctions extends AbstractPage {

	public PageObjectCommonFunctions(WebDriver driver) {
		super(driver);
	}

	protected WebElement waitUntilVisible(By locator) {
		WebDriverWait wait = new WebDriverWait(driver, 20);
		return wait.until(refreshed(ExpectedConditions.visibilityOfElementLocated(locator)));
	}

	private <T> ExpectedCondition<T> refreshed(
			final Function<WebDriver, T> originalFunction) {

		return new ExpectedCondition<T>() {
			public T apply(WebDriver webdriver) {
				try {
					return originalFunction.apply(webdriver);
				} catch (StaleElementReferenceException sere) {
					throw new NoSuchElementException("Element stale.", sere);
				}
			}
		};

	}
	
	/**
	 * Get url function
	 * @return
	 */
	public String getUrl() {
		
		String url = null;
		url = driver.getCurrentUrl();
		return url;
		
	}
}
